package com.library.config;

import com.library.security.JwtTokenProvider;
import com.library.security.UserDetailsServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启方法级权限控制
public class WebSecurityConfig {

    @Resource
    private UserDetailsServiceImpl userDetailsService;
    @Resource
    private JwtTokenProvider jwtTokenProvider;

    // 1. 密码加密器（Bean 名称唯一）
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    // 2. 认证管理器（Bean 名称唯一）
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }

    // 3. 内部类：JWT 认证过滤器（仅在配置类内部定义，不单独创建类）
    public static class JwtAuthenticationFilter extends org.springframework.web.filter.OncePerRequestFilter {
        private final JwtTokenProvider jwtTokenProvider;

        // 构造器：注入 JwtTokenProvider
        public JwtAuthenticationFilter(JwtTokenProvider jwtTokenProvider) {
            this.jwtTokenProvider = jwtTokenProvider;
        }

        @Override
        protected void doFilterInternal(javax.servlet.http.HttpServletRequest request,
                                        javax.servlet.http.HttpServletResponse response,
                                        javax.servlet.FilterChain filterChain)
                throws javax.servlet.ServletException, java.io.IOException {
            try {
                // 从请求头获取 Token（格式：Bearer xxx）
                String token = getTokenFromRequest(request);
                // 验证 Token 并设置认证信息到 SecurityContext
                if (token != null && jwtTokenProvider.validateToken(token)) {
                    String username = jwtTokenProvider.getUsernameFromToken(token);
                    // 构建认证对象（简化处理，无权限列表）
                    org.springframework.security.authentication.UsernamePasswordAuthenticationToken auth =
                            new org.springframework.security.authentication.UsernamePasswordAuthenticationToken(
                                    username, null, java.util.Collections.emptyList()
                            );
                    // 设置请求详情
                    auth.setDetails(new org.springframework.security.web.authentication.WebAuthenticationDetailsSource()
                            .buildDetails(request));
                    // 将认证信息存入上下文
                    org.springframework.security.core.context.SecurityContextHolder.getContext().setAuthentication(auth);
                }
            } catch (Exception e) {
                logger.error("JWT 认证失败：", e);
            }
            // 继续执行过滤器链
            filterChain.doFilter(request, response);
        }

        // 辅助方法：从请求头提取 Token
        private String getTokenFromRequest(javax.servlet.http.HttpServletRequest request) {
            String bearerToken = request.getHeader("Authorization");
            if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
                return bearerToken.substring(7); // 截取 "Bearer " 后的 Token 部分
            }
            return null;
        }
    }

    // 4. 安全过滤器链配置（注册内部 Filter，避免重复）
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .csrf().disable() // 前后端分离，关闭 CSRF
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 无状态会话（JWT 不需要 session）
                .and()
                .authorizeRequests()
                // 放行前端静态资源和登录接口
                .antMatchers("/", "/index.html", "/components/**", "/http-vue-loader.js").permitAll()
                .antMatchers("/api/auth/login").permitAll()
                // 其他接口需认证
                .anyRequest().authenticated();

        // 注册 JWT 过滤器（使用内部类，避免 bean 重复）
        http.addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}